package com.asman.worker.gallery

import android.database.ContentObserver
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.os.Process
import android.provider.MediaStore
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import com.asman.base.lib.utils.PermissionUtils
import com.asman.base.lib.utils.StatusBarUtil
import com.asman.customerview.SpacesItemDecoration
import com.asman.worker.R
import com.multipleimageselect.helpers.Constants
import init
import kotlinx.android.synthetic.main.activity_gallery_list.*
import kotlinx.android.synthetic.main.layout_toolbar.*
import java.io.File
import java.lang.ref.WeakReference
import java.util.*

/**
 * Created by Darshan on 4/18/2015.
 */
class GalleryListActivity : AppCompatActivity() {
    private var images = arrayListOf<Image>()
    private var album: String? = null

    private var adapter: ImageAdapter? = null

//    var countSelected: Int = 0

    private var observer: ContentObserver? = null
    private var handler: Handler? = null
    private var thread: Thread? = null
    private val projection = arrayOf(
        MediaStore.Images.Media._ID,
        MediaStore.Images.Media.DISPLAY_NAME,
        MediaStore.Images.Media.DATA,
        MediaStore.Images.Media.SIZE
    )
//    internal var toolbar: Toolbar

//    private val selected: ArrayList<Image>
//        get() {
//            val selectedImages = ArrayList<Image>()
//            var i = 0
//            val l = images!!.size
//            while (i < l) {
//                if (images!![i].isSelected) {
//                    selectedImages.add(images!![i])
//                }
//                i++
//            }
//            return selectedImages
//        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gallery_list)
        StatusBarUtil.setDarkModel(this)
//        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT//强制竖屏
//        setView(layout_image_select)

//        toolbar = findViewById(R.id.toolbar)
//        setSupportActionBarWithBack(toolbar, com.jph.takephoto.R.drawable.ic_back) { v -> finish() }
//        toolbar.title = countSelected.toString() + "/" + Constants.limit

        val intent = intent
        if (intent == null) {
            finish()
            return
        }
        album = intent.getStringExtra(Constants.INTENT_EXTRA_ALBUM)
        toolbar.init(this@GalleryListActivity, title = album)
//                    text_view_error = findViewById(R.id.text_view_error)
        text_view_error?.visibility = View.INVISIBLE

//                    progress_bar_image_select = findViewById(R.id.progress_bar_image_select)
//                    grid_view_image_select = findViewById(R.id.grid_view_image_select)
        grid_view_image_select?.layoutManager = GridLayoutManager(this@GalleryListActivity, 3)
        grid_view_image_select?.addItemDecoration(SpacesItemDecoration(4))
    }

    internal class MyHandler(activity: GalleryListActivity) : Handler() {
        var weakReference: WeakReference<GalleryListActivity> = WeakReference(activity)

        override fun handleMessage(msg: Message) {
            when (msg.what) {
                Constants.PERMISSION_GRANTED -> weakReference.get()!!.loadImages()
                Constants.FETCH_STARTED -> {
                    weakReference.get()!!.progress_bar_image_select!!.visibility = View.VISIBLE
                    weakReference.get()!!.grid_view_image_select!!.visibility = View.INVISIBLE
                }
                Constants.FETCH_COMPLETED -> if (weakReference.get()!!.adapter == null) {
                    weakReference.get()!!.adapter =
                        ImageAdapter(weakReference.get()!!.images)
                    weakReference.get()!!.grid_view_image_select!!.adapter =
                        weakReference.get()!!.adapter
                    weakReference.get()!!.progress_bar_image_select!!.visibility = View.INVISIBLE
                    weakReference.get()!!.grid_view_image_select!!.visibility = View.VISIBLE
                }
                Constants.ERROR -> {
                    weakReference.get()!!.progress_bar_image_select!!.visibility = View.INVISIBLE
                    weakReference.get()!!.text_view_error!!.visibility = View.VISIBLE
                }
                else -> super.handleMessage(msg)
            }
        }
    }

    override fun onStart() {
        super.onStart()
        handler = MyHandler(this)
        observer = object : ContentObserver(handler) {
            override fun onChange(selfChange: Boolean) {
                loadImages()
            }
        }
        contentResolver.registerContentObserver(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            false,
            observer!!
        )
//        checkPermission()

        PermissionUtils.requestReadWriteSDCard(this,
            object : PermissionUtils.OnPermissionListener() {
                override fun success() {
                    sendMessage(Constants.PERMISSION_GRANTED)
                }
            })
    }

    override fun onStop() {
        super.onStop()

        stopThread()

        contentResolver.unregisterContentObserver(observer!!)
        observer = null

        if (handler != null) {
            handler!!.removeCallbacksAndMessages(null)
            handler = null
        }
    }

//    override fun onOptionsItemSelected(item: MenuItem): Boolean {
//        if (item.itemId == com.jph.takephoto.R.id.menu_item_add_image) {
//            if (countSelected > 0)
//                sendIntent()
//            else
//                Toast.makeText(this, "请选择图片", Toast.LENGTH_SHORT).show()
//        } else if (item.itemId == android.R.id.home) {
//            onBackPressed()
//        }
//        return super.onOptionsItemSelected(item)
//    }
//
//    override fun onCreateOptionsMenu(menu: Menu): Boolean {
//        menuInflater.inflate(com.jph.takephoto.R.menu.menu_contextual_action_bar, menu)
//        return super.onCreateOptionsMenu(menu)
//    }

//    fun toggleSelection(image: Image) {
//        if (!image.isSelected && countSelected >= Constants.limit) {
//            Toast.makeText(
//                applicationContext,
//                String.format(
//                    getString(com.jph.takephoto.R.string.limit_exceeded),
//                    Constants.limit
//                ),
//                Toast.LENGTH_SHORT
//            )
//                .show()
//            return
//        }
//        image.isSelected = !image.isSelected
//        if (image.isSelected) {
//            countSelected++
//        } else {
//            countSelected--
//        }
//        adapter!!.notifyItemChanged(images!!.indexOf(image))
//    }

//    private fun sendIntent() {
//        val intent = Intent()
//        intent.putParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES, selected)
//        setResult(Activity.RESULT_OK, intent)
//        finish()
//    }

    private fun loadImages() {
        startThread(ImageLoaderRunnable())
    }

    private inner class ImageLoaderRunnable : Runnable {
        override fun run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)
            /*
            If the adapter is null, this is first duration this activity's view is
            being shown, hence send FETCH_STARTED message to initType progress bar
            while images are loaded from phone
             */
            if (adapter == null) {
                sendMessage(Constants.FETCH_STARTED)
            }

            var file: File
//            val selectedImages = HashSet<Long>()
//            var image: Image
            var i = 0
            val l = images.size
//            while (i < l) {
//                image = images[i]
//                file = File(image.path)
//                if (file.exists() && file.length() > 0 && image.isSelected) {
//                    selectedImages.add(image.id)
//                }
//                i++
//            }

            val cursor = contentResolver.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection,
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME + " =?",
                album?.let { arrayOf(it) },
                MediaStore.Images.Media.DATE_ADDED
            )
            if (cursor == null) {
                sendMessage(Constants.ERROR)
                return
            }

            /*
            In case this runnable is executed to onChange calling loadImages,
            using countSelected variable can result in a race condition. To avoid that,
            tempCountSelected keeps track of number of selected images. On handling
            FETCH_COMPLETED message, countSelected is assigned value of tempCountSelected.
             */
            var tempCountSelected = 0
            val temp = ArrayList<Image>()
            if (cursor.moveToLast()) {
                do {
                    if (Thread.interrupted()) {
                        return
                    }

                    val id = cursor.getLong(cursor.getColumnIndex(projection[0]))
                    val name = cursor.getString(cursor.getColumnIndex(projection[1]))
                    val path = cursor.getString(cursor.getColumnIndex(projection[2]))
                    val size = cursor.getString(cursor.getColumnIndex(projection[3]))
//                    val isSelected = selectedImages.contains(id)
//                    if (isSelected) {
//                        tempCountSelected++
//                    }

                    file = File(path)
                    if (file.length() > 0) {
                        if (file.exists()) {
                            temp.add(Image(id, name, path, size, "0"))
                        } else {
                            file.delete()
                        }
                    } else {
                        file.delete()
                    }
                } while (cursor.moveToPrevious())
            }
            cursor.close()

            images.clear()
            images.addAll(temp)

            sendMessage(Constants.FETCH_COMPLETED, tempCountSelected)
        }
    }

    private fun startThread(runnable: Runnable) {
        stopThread()
        thread = Thread(runnable)
        thread!!.start()
    }

    private fun stopThread() {
        if (thread == null || !thread!!.isAlive) {
            return
        }

        thread!!.interrupt()
        try {
            thread!!.join()
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }

    }

    private fun sendMessage(what: Int, arg1: Int = 0) {
        if (handler == null) {
            return
        }

        val message = handler!!.obtainMessage()
        message.what = what
        message.arg1 = arg1
        message.sendToTarget()
    }

//    override fun permissionGranted() {
//        sendMessage(Constants.PERMISSION_GRANTED)
//    }

//    override fun hideViews() {
//        progress_bar_image_select!!.visibility = View.INVISIBLE
//        grid_view_image_select!!.visibility = View.INVISIBLE
//    }
}
